package cd.tools_test.usbhelper.view;


import android.app.Activity;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cd.tools_test.R;
import cd.tools_test.usbhelper.adapter.DeviceAdapter;
import cd.usbhelper.IUsbhelperListener;
import cd.usbhelper.UsbHelperClient;

public class UsbActivity extends Activity implements OnClickListener {

    private static final String TAG = "cd";
    private static final int MY_PERMISSION_REQUEST_CONSTANT = 1;
    private static final int DEFAULT_RESPONSE_LEN = 64;
    private DeviceAdapter mDeviceAdapter;
    private ListView listView_device;
    private UsbHelperClient mUsbHelperClient;
    private Button btn_bt_search, btn_bt_close, btn_send;
    private TextView tv_output;
    private EditText et_input;
    private ListView lv_devices;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usb);

        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mUsbHelperClient!=null)
            mUsbHelperClient.disConnectDevice();
    }

    private void initView() {
        ((Button)findViewById(R.id.btn_bt_search)).setText("搜索USB");
        btn_bt_search = (Button) findViewById(R.id.btn_bt_search);
        btn_bt_close = (Button) findViewById(R.id.btn_bt_close);
        btn_send = ((Button) findViewById(R.id.btn_send));

        btn_bt_search.setOnClickListener(this);
        btn_bt_close.setOnClickListener(this);
        btn_send.setOnClickListener(this);

        tv_output = (TextView) findViewById(R.id.tv_output);
        et_input = (EditText) findViewById(R.id.et_input);
        tv_output.setMovementMethod(ScrollingMovementMethod.getInstance());


        lv_devices = (ListView) findViewById(R.id.lv_devices);
        mDeviceAdapter = new DeviceAdapter(this);
        mDeviceAdapter.setOnDeviceClickListener(new DeviceAdapter.OnItemClickListener() {
            @Override
            public void onConnect(DeviceAdapter.Item item) {
                append_tv_output("正在连接...");
                connect(item.getObject());
            }

            @Override
            public void onDisConnect(DeviceAdapter.Item item) {
                mUsbHelperClient.disConnectDevice();
            }

        });
        listView_device = (ListView) findViewById(R.id.lv_devices);
        listView_device.setAdapter(mDeviceAdapter);
        setListViewHeightBasedOnChildren(listView_device);
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_bt_search) {
            SearchBtDevices();
        } else if (viewId == R.id.btn_bt_close) {

        } else if (viewId == R.id.btn_send) {
            send();
        }
    }

    private class ReadThread extends Thread {

        private byte[] response = new byte[DEFAULT_RESPONSE_LEN];

        @Override
        public void run() {
            super.run();

            while (true) {
                final int ret = mUsbHelperClient.readMessage( usbEpIn,response, 1000);
                Log.d("chenda","read ret = " + ret);
                if (ret <= 0)
                    continue;
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        StringBuffer stringBuffer = new StringBuffer();
                        for(int i=0;i<ret;i++){
                            stringBuffer.append(String.format("%x",response[i]));
                        }
                        append_tv_output(stringBuffer.toString());
                    }
                });

            }
        }
    }

    private void send() {
        String input = et_input.getText().toString().trim();
        input = input.replace(" ", "");
        if(input.length()==0)
            return;
//        byte[] cmd = new byte[64];
        byte[] src = hex2ByteArray(input);
//        System.arraycopy(src,0,cmd,0,src.length);
        int ret = mUsbHelperClient.sendMessage(usbEpOut,src,5000);
        Log.d("chenda","send ret = " + ret);
        if (ret < 0) {
            append_tv_output("发送失败："+ret);
            return;
        }
//		append_tv_output(ByteArray2Hex.parse(cmd));
    }

    private UsbEndpoint usbEpOut,usbEpIn;
    private void connect(Object o) {
        mUsbHelperClient.connectDevice(((UsbDevice) o), new IUsbhelperListener() {

            @Override
            public void onSuccess(UsbDeviceConnection deviceConnection, List<UsbEndpoint> listUsbEp) {
                append_tv_output("连接完成");
                listView_device.setVisibility(View.GONE);
                Log.d("cd", "connectDevice  onSuccess()  ");
                usbEpOut =listUsbEp.get(1);
                usbEpIn = listUsbEp.get(0);
                new ReadThread().start();
            }

            @Override
            public void onError(int errno) {
                Log.d("cd", " connectDevice onError " + errno);
                append_tv_output("连接出错：" + errno);
            }

        });
    }

    private void SearchBtDevices() {
        if (mUsbHelperClient != null)
            mUsbHelperClient.disConnectDevice();

        mUsbHelperClient = new UsbHelperClient(this);
        listView_device.setVisibility(View.VISIBLE);
        HashMap<String, UsbDevice> devices = mUsbHelperClient.getDeviceList();

        for (String key : devices.keySet()) {
            Log.d(TAG, "key = " + key);
            Log.d(TAG, "getDeviceName() = " + devices.get(key).getDeviceName());
            Log.d(TAG, "getDeviceId() = " + devices.get(key).getDeviceId());
            Log.d(TAG, "getVendorId() = " + devices.get(key).getVendorId());
            Log.d(TAG, "getProductId() = " + devices.get(key).getProductId());
            Log.d(TAG, "getDeviceClass() = " + devices.get(key).getDeviceClass());

            DeviceAdapter.Item item = mDeviceAdapter.new Item(devices.get(key).getDeviceName(), "VendorId : " + devices.get(key).getVendorId() + " VendorId : " + devices.get(key).getProductId(), devices.get(key));
            mDeviceAdapter.addDevice(item);
            mDeviceAdapter.notifyDataSetChanged();
        }


    }

    private void append_tv_output(String s) {
        tv_output.append(s);
        tv_output.append("\n");

        int offset = tv_output.getLineCount() * tv_output.getLineHeight();
        if (offset > tv_output.getHeight()) {
            tv_output.scrollTo(0, offset - tv_output.getHeight());
        }
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {

        // 获取ListView对应的Adapter

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {

            return;

        }

        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目

            View listItem = listAdapter.getView(i, null, listView);

            listItem.measure(0, 0); // 计算子项View 的宽高

            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度

        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        // listView.getDividerHeight()获取子项间分隔符占用的高度

        // params.height最后得到整个ListView完整显示需要的高度

        listView.setLayoutParams(params);

    }

    public static byte[] hex2ByteArray(String hex) {
        hex = hex.toLowerCase();
        int length = hex.length() / 2;
        byte buf[] = new byte[length];
        int flag = 0;
        if (hex.equals("")) {
            return null;
            // hex=new String(hex.getBytes(),"GBK");

        } else {
            for (int s = 0; s < hex.length(); s++) {
                char ch = hex.charAt(s);
                if ((isChineseChar(hex)) || ((ch >= 0) && (ch <= 47))
                        || ((ch >= 58) && (ch <= 64)) || ((ch >= 71) && (ch <= 96)) || ((ch >= 103) && (ch <= 127))) {
                    // tvOutput.append("Can be a hexadecimal number!");
                    flag = 1;
                } else {
                    if (s > 0 && s % 2 != 0) {
                        buf[s / 2] = (byte) (16 * Integer.valueOf(hex.substring(s - 1, s),16)
                                + Integer.valueOf(hex.substring(s, s + 1),16));
                    }
                }
                if (flag == 1) {
                    return null;
                }
            }
            return buf;
        }
    }

    public static boolean isChineseChar(String str) {
        boolean temp = false;
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            temp = true;
        }
        return temp;
    }


}
